package io.xxx.xbutler.core.check;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import io.xxx.xbutler.domain.RoomCategory;
import io.xxx.xbutler.domain.Store;
import io.xxx.xbutler.domain.task.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Order(60)
@Component
public class ProductVenueChecker extends ProductChecker {

    @Override
    public CheckError check(PushContext context) {
        LocalDateTime now = LocalDateTime.now();
        Task task = context.getTask();
        Receiver receiver = context.getReceiver();
        String storeCode = receiver.getStoreCode();
        Store store = context.getStore() != null ? context.getStore() : context.getCutomStore();

        List<TaskItem> taskItems = context.getTaskItems();
        for (TaskItem taskItem : taskItems) {
            if (!taskItem.assign(MessageType.MINI_PROGRAM, ContentType.PRODUCT_VENUE) || store == null) {
                continue;
            }

            JSONObject content = taskItem.getContent();
            JSONObject venue = content.getJSONObject("venue");
            JSONArray products = venue.getJSONArray("products");

            List<JSONObject> remainingProducts = new ArrayList<>(products.size());
            for (Object o : products) {
                JSONObject product = JSONObject.from(o);
                String skuSn = product.getString("skuSn");
                CheckError checkError = checkProduct(task, taskItem, store, skuSn, now);
                if (checkError != null) {
                    continue;
                }
                remainingProducts.add(product);
            }

            venue.put("products", remainingProducts);
            if (remainingProducts.size() < 2) {
                log.info("商品数量不足[taskId:{}, storeId:{}, storeCode:{}, products:{}]",
                        task.getId(), store.getId(), storeCode, JSON.toJSONString(remainingProducts));
                return CheckError.StoreAreaNotMatch;
            }
        }
        return null;
    }

    @Override
    public boolean supports(PushContext context) {
        Task task = context.getTask();
        return task.getScene() == TaskScene.Push && task.getRoomCategory() == RoomCategory.CustomerRoom;
    }
}
